package org.budo.mongo.jdbc.driver.resultset;

import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;

import org.budo.mongo.jdbc.driver.BudoMongoJdbcResultSet;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcResultSetMetaData;
import org.budo.mongo.jdbc.driver.parser.StatementParserUtil;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;

/**
 * @author lmw
 */
public class BasicDbListResultSet extends BudoMongoJdbcResultSet {
    private BasicDBList basicDBList;

    private int currentRowIndex = -1;

    public BasicDbListResultSet() {}

    public BasicDbListResultSet(BasicDBList basicDBList) {
        this.basicDBList = basicDBList;
    }

    public ResultSetMetaData getMetaData() throws SQLException {
        if (null == super.getMetaData()) {
            String[] columnNames = new String[0];
            if (null != this.basicDBList && !this.basicDBList.isEmpty()) {
                Object rowObj = this.basicDBList.get(0);
                BasicDBObject row = (BasicDBObject) rowObj;
                columnNames = row.keySet().toArray(columnNames);
            }
            BudoMongoJdbcResultSetMetaData metaData = StatementParserUtil.resultSetMetaData(columnNames, Types.JAVA_OBJECT, Long.class);

            super.setMetaData(metaData);
        }

        return super.getMetaData();
    }

    public boolean next() throws SQLException {
        if (null == this.basicDBList) {
            return false;
        }

        this.currentRowIndex++;
        return this.basicDBList.size() > this.currentRowIndex;
    }

    public Object getObject(String columnLabel) throws SQLException {
        Object rowObj = this.basicDBList.get(this.currentRowIndex);
        BasicDBObject row = (BasicDBObject) rowObj;
        return row.get(columnLabel);
    }
}